package com.weitu.contractor.controller;

import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.SafeProductCert;
import com.weitu.contractor.entity.SafeProductCertCriteria;
import com.weitu.contractor.entity.SafeProductCertHistory;
import com.weitu.contractor.entity.SafeProductCertHistoryCriteria;
import com.weitu.contractor.service.SafeProductCertHistoryService;
import com.weitu.contractor.service.SafeProductCertService;
import com.weitu.paging.DataGridPagination;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/13
 */
@Controller
@RequestMapping(value = "contractor/safeProductCert")
public class SafeProductCertController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/safeProductCert";
    private final SafeProductCertService safeProductCertService;
    private final SafeProductCertHistoryService safeProductCertHistoryService;

    @Autowired
    public SafeProductCertController(SafeProductCertService safeProductCertService, SafeProductCertHistoryService safeProductCertHistoryService) {
        this.safeProductCertService = safeProductCertService;
        this.safeProductCertHistoryService = safeProductCertHistoryService;
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object certListAjax(HttpServletRequest request, String sort, String contractorId) throws Exception {
        SafeProductCertCriteria criteria = new SafeProductCertCriteria();
        criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andContractorIdEqualTo(contractorId);

        int count = safeProductCertService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            criteria.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        criteria.setPageView(pageView);

        List<SafeProductCert> safeProductCerts = safeProductCertService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(safeProductCerts);
    }

    @SystemLog(module = "承包商信息", methods = "更新上传证书附件信息")
    @ResponseBody
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public AjaxResult certUploadAjax(String id, String contractorId) throws Exception {
        if (StringUtils.isEmpty(contractorId)) {
            return fail("附件信息保存失败！");
        }
        SafeProductCert safeProductCert = new SafeProductCert();
        safeProductCert.setId(id);
        safeProductCert.setUpdateUserId(getSessionUser().getId());
        safeProductCert.setUpdateDeptId(getSessionUser().getDepartment().getId());
        safeProductCert.setUpdateTime(DateTimeUtil.formatterDateTime());
        safeProductCert.setContractorId(contractorId);
        if (safeProductCertService.updateByPrimaryKeySelective(safeProductCert) > 0) {
            if (!AccessoryUtil.saveAccerssoryInfo(id)) {
                return fail("附件信息保存失败！");
            }
            return success("附件信息保存成功！");
        }
        return fail("附件信息保存失败！");
    }

    @SystemLog(module = "承包商信息", methods = "更新证书信息")
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public AjaxResult certUpdateAjax(SafeProductCert safeProductCert) throws Exception {
        if (safeProductCertService.checkIfExtraSafeCertExist(safeProductCert.getContractorId(), safeProductCert.getId()) && "安全生产许可证".equals(safeProductCert.getName())) {
            return fail("保存失败，已有安全生产许可证！");
        }
        if (safeProductCertService.checkIfCertCodeExist(safeProductCert.getContractorId(), safeProductCert.getCertCode())) {
            return fail("保存失败，存在相同证书编号的数据!");
        }
        safeProductCert.setUpdateUserId(getSessionUser().getId());
        safeProductCert.setUpdateDeptId(getSessionUser().getDepartment().getId());
        safeProductCert.setUpdateTime(DateTimeUtil.formatterDateTime());
        if (safeProductCertService.updateByPrimaryKeySelective(safeProductCert) > 0) {
            SafeProductCertHistory history = new SafeProductCertHistory();
            history.setId(IDGenerator.getId());
            history.setAddUserId(getSessionUser().getId());
            history.setAddDeptId(getSessionUser().getDepartment().getId());
            history.setAddTime(DateTimeUtil.formatterDateTime());
            history.setCertId(safeProductCert.getId());
            history.setContractorId(safeProductCert.getContractorId());
            history.setName(safeProductCert.getName());
            history.setCertCode(safeProductCert.getCertCode());
            history.setValidStartDate(safeProductCert.getValidStartDate());
            history.setValidEndDate(safeProductCert.getValidEndDate());
            safeProductCertHistoryService.insertSelective(history);
            return success("保存成功！");
        }
        return fail("保存失败！");
    }

    @SystemLog(module = "承包商信息", methods = "添加证书信息")
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult certSaveAjax(String id, String contractorId) throws Exception {
        if (StringUtils.isEmpty(contractorId)) {
            return fail("添加失败！");
        }
        SafeProductCert safeProductCert = new SafeProductCert();
        safeProductCert.setId(id);
        safeProductCert.setAddUserId(getSessionUser().getId());
        safeProductCert.setAddDeptId(getSessionUser().getDepartment().getId());
        safeProductCert.setAddTime(DateTimeUtil.formatterDateTime());
        safeProductCert.setContractorId(contractorId);
        if (safeProductCertService.insertSelective(safeProductCert) > 0) {
            return success("添加成功！");
        }
        return fail("添加失败！");
    }

    @SystemLog(module = "承包商信息", methods = "删除证书信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult certDeleteAjax(String id) throws Exception {
        if (safeProductCertService.deleteByPrimaryKey(id) > 0) {
            return success("删除成功！");
        }
        return fail("删除失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/historyList", method = RequestMethod.POST)
    public Object certHistoryListAjax(HttpServletRequest request, String certId, String contractorId) throws Exception {
        SafeProductCertHistoryCriteria criteria = new SafeProductCertHistoryCriteria();
        criteria.createCriteria()
                .andDelStateEqualTo(0)
                .andContractorIdEqualTo(contractorId)
                .andCertIdEqualTo(certId);

        int count = safeProductCertHistoryService.countByCriteria(criteria);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        criteria.setPageView(pageView);

        List<SafeProductCertHistory> safeProductCertHistories = safeProductCertHistoryService.selectByCriteria(criteria);

        return dataGridPagination.flushDataGridData(safeProductCertHistories);
    }

    @ResponseBody
    @RequestMapping(value = "/selectByContractorId", method = RequestMethod.GET)
    public AjaxResult selectByContractorId(String contractorId) throws Exception {
        List<SafeProductCert> safeProductCerts = safeProductCertService.selectByContractorId(contractorId);
        if (safeProductCerts.size() == 1){
            return success("数据获取成功！",safeProductCerts.get(0));
        }else {
            return fail("数据获取失败！");
        }
    }
}
